//
//  ST_GiftAssetProvider.swift
//  btvideo
//
//  Created by Jason on 2021/10/22.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import RxCocoa
import RxSwift
import SVGAPlayer
import Alamofire
import RxAlamofire

enum GiftAssetProvideError:Error{
    /// 无效的URL
    case invalidUrl
    /// 无效目录
    case invalidDirectory
    /// 未找到缓存文件
    case notFound
    /// 解析失败
    case parsingFailed
}

struct ST_GiftAssetProvider {
}

extension ST_GiftAssetProvider{
    
    /// 缓存URL 的 Observable
    static func checkoutSVGAFileSession(urlStr:String)->Observable<Void>{
        
      
        guard  var localPath = SC.svga_temporary_directory else {
            return Observable.error(GiftAssetProvideError.invalidDirectory)
        }
        
        let cacheKey = urlStr.md5_string
        
        localPath.appendPathComponent(cacheKey)
        
        print("[bug1077]- [干着急] localPath = ",localPath.path)
        
        if FileManager.default.fileExists(atPath: localPath.path){
            
            print("[bug1077]-[干着急]--查询到文件啦")
            
            return Observable.just(())
            
        }else{
            
            print("[bug1077]-[干着急]--没查到文件")
            
           return  Observable<Void>.create { observer -> Disposable in
                
                ST_JVAlamofire.download(url: urlStr, savedPath: localPath.path) {
                    
                    print("[bug1077] [干着急] 保存 SVGA 动画正确")
                    
                    observer.onNext(())
                    
                } failure: { (code, err) in
                    
                    print("[bug1077] [干着急] SVGA 动画错误")
                    
                    observer.onError(GiftAssetProvideError.invalidUrl)
                }
               
               return Disposables.create()
            }
            
        }
    }
    
    static func checkoutSVGAFile(url:String?){
        
            //        url.md5_string
            guard let remoteURL = url , var localPath = SC.svga_temporary_directory else { return  }
            
            localPath.appendPathComponent(remoteURL.md5_string)
            
            print("[bug1077]提前保存 localPath = ",localPath.path)
            
            if FileManager.default.fileExists(atPath: localPath.path){
                print("[bug1077]提前保存 SVGA 查询到文件啦")
                return
            }
            
        ST_JVAlamofire.download(url: remoteURL, savedPath: localPath.path) {
                
                print("[bug1077]提前保存 SVGA 动画正确")
                
            } failure: { (code, err) in
                
                print("[bug1077]提前保存 SVGA 动画错误")
            }
    }
    
    /**
     播放SVGA 文件
     */
    static func playSVGASession(urlString:String?)->Observable<SVGAVideoEntity>{
        
        guard let url = urlString?.url else {
            return Observable.error(GiftAssetProvideError.invalidUrl)
        }
        
        guard  var localPath = SC.svga_temporary_directory else {
            return Observable.error(GiftAssetProvideError.invalidDirectory)
        }
        
        let cacheKey = url.absoluteString.md5_string
        
        localPath.appendPathComponent(cacheKey)
        
        return ST_GiftAssetProvider.checkoutSVGAFileSession(urlStr: url.absoluteString).flatMapLatest { _ -> Observable<SVGAVideoEntity> in
            
            
            let single:Observable<SVGAVideoEntity> = Observable.create { observer -> Disposable in
                
                guard let localData = try? Data(contentsOf: localPath) else{
                    
                    observer.onError(GiftAssetProvideError.notFound)
                    
                    return Disposables.create()
                }
                
                let parser = SVGAParser()
                
                
                if FileManager.default.fileExists(atPath: localPath.path){
                    print("[bug1077] 解析之前 true")
                }else{
                    print("[bug1077] 解析之前 false")
                }
//
                
                
                parser.parse(with: localData, cacheKey: cacheKey) { (videoItem) in
                    
                    print("[bug1077]提前保存 本地有 解析成功")
                    observer.onNext(videoItem)
                    observer.onCompleted()
                    
                } failureBlock: { (e) in
                    
                    print("[bug1077]提前保存 本地有 解析❌")
                    observer.onError(GiftAssetProvideError.parsingFailed)
                }
                
                return Disposables.create()
            }
            
            return single
        }
        
    }
    
    
}

